<template>
  <div @click="onClick" @mouseenter="onMouseEnter">
    <component
      :is="config.component"
      v-if="config.component.startsWith('SVG')"
      v-show="showCondition"
      ref="component"
      class="component"
      :style="getSVGStyle(config.style)"
      :prop-value="aliasPropValue"
      :element="config"
      :request="config.request"
      :linkage="config.linkage"
      :remote-data="remoteData"
      @generalEvent="generalEvent"
    />
    <component
      :is="config.component"
      v-else
      v-show="showCondition"
      ref="component"
      class="component"
      :style="getStyle(config.style)"
      :prop-value="aliasPropValue"
      :element="config"
      :request="config.request"
      :linkage="config.linkage"
      :remote-data="remoteData"
      @generalEvent="generalEvent"
    />
  </div>
</template>

<script setup lang="ts">
import { eventBus, getStyle, getSVGStyle } from "@visual/utils";
import useEvents from "@visual/utils/useEvents";
import { computed, onMounted, reactive, ref, toRaw } from "vue";
const props = defineProps({
  config: {
    type: Object,
    required: true,
    default: () => {}
  }
});
const remoteData = ref({ ltitle: "123", ltip: "321" });
const component = ref(null);
let eventParams = {};
let { offEvent, showCondition } = useEvents({
  curComp: component,
  curConfig: props.config
});
//绑定数据别名
const alias = ref({});
const aliasPropValue = computed(() => {
  const cState = {};
  if (Object.keys(alias.value).length > 0) {
    Object.keys(alias.value).forEach(key => {
      if (alias.value[key]) {
        cState[key] = remoteData.value[alias.value[key]];
      }
    });
  } else {
    return reactive(props.config.propValue);
  }

  return reactive(cState);
});
onMounted(() => {
  //event数据整理为{eventName: {key: value}}形式
  eventParams = props.config.events?.reduce((a, c) => {
    const { event, params } = c;
    a[event] = params.reduce((acc, cur) => {
      acc[cur.key] = cur.value;
      return acc;
    }, {});
    return a;
  }, {});
  if (props.config.component === "filterMenu" || eventParams["compFilter"]) {
    offEvent("compFilter");
  }
  if (props.config?.dataAliase) {
    alias.value = toRaw(props.config?.dataAliase);
  }
});
function onClick() {
  console.log("click--->", eventParams);
}
function onMouseEnter() {}
function generalEvent(params) {
  const { type, compEmitData } = params;
  let coParams = eventParams[type] ? { ...eventParams[type], compEmitData } : { compEmitData };
  eventBus.emit(type, { emitParams: coParams, emitConfig: props.config });
}
</script>

<style lang="scss" scoped>
.component {
  position: absolute;
}
</style>
